<?php declare(strict_types=1);

/**
 * @package PluginMaker (Light Portal)
 * @link https://custom.simplemachines.org/index.php?mod=4244
 * @author Bugo <bugo@dragomano.ru>
 * @copyright 2021-2025 Bugo
 * @license https://spdx.org/licenses/GPL-3.0-or-later.html GPL-3.0-or-later
 *
 * @category plugin
 * @version 24.09.25
 */

namespace LightPortal\Plugins\PluginMaker;

use Bugo\Compat\ErrorHandler;
use Bugo\Compat\Lang;

if (! defined('LP_NAME'))
	die('No direct access...');

class Builder
{
	protected string $path;

	public function __construct(protected string $name)
	{
		$this->path = LP_ADDON_DIR . DIRECTORY_SEPARATOR . $name;
	}

	public function create(string $content): Builder
	{
		$isDirReady = mkdir($this->path);

		if (! $isDirReady) {
			ErrorHandler::fatal(Lang::$txt['lp_plugin_maker']['addon_dir_not_created'], false);
		}

		copy(LP_ADDON_DIR . DIRECTORY_SEPARATOR . 'index.php', $this->path . DIRECTORY_SEPARATOR . 'index.php');

		$this->addSecurityCheck($content);

		file_put_contents($this->path . DIRECTORY_SEPARATOR . $this->name . '.php', $content, LOCK_EX);

		return $this;
	}

	public function createLangs(array $languages = []): Builder
	{
		$isDirReady = mkdir($this->path . DIRECTORY_SEPARATOR . 'langs');

		if (! $isDirReady) {
			ErrorHandler::fatal(Lang::$txt['lp_plugin_maker']['lang_dir_not_created']);
		}

		copy($this->path . DIRECTORY_SEPARATOR . 'index.php', $this->path . DIRECTORY_SEPARATOR . 'langs' . DIRECTORY_SEPARATOR . 'index.php');

		foreach ($languages as $lang => $data) {
			foreach ($data as $content) {
				file_put_contents($this->path . DIRECTORY_SEPARATOR . 'langs' . DIRECTORY_SEPARATOR . $lang . '.php', $content, FILE_APPEND | LOCK_EX);
			}
		}

		return $this;
	}

	private function addSecurityCheck(string &$content): void
	{
		$message = <<<XXX
	if (! defined('LP_NAME'))
		die('No direct access...');

	/**
	 * Generated by PluginMaker
	 */
	XXX;

		$content = str_replace('/**
 * Generated by PluginMaker
 */', $message, $content);
	}
}
